<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * @param Request $request
     * @param $key @文件键值
     * @return array
     * @return @param original_name 文件原名
     * @return @param url 文件相对路径
     */
    public function fileUpload(Request $request,$key)
    {
        $file = $request->file($key);
        if(!$file)
            return ['status' => 0, 'msg' => $key.' 请选择文件'];
        // 文件是否上传成功
        if ($file->isValid()) {

            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg

            // 上传文件
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            //这里的uploads是配置文件的名称
            $bool = Storage::disk('public')->put($filename, file_get_contents($realPath));
            if ($bool) {
                return ['status' => 1, 'url' => '/uploads/files/'.$filename, 'original_name' => $originalName];
            } else {
                return ['status' => 0, 'msg' => '文件上传失败'];
            }

        }
    }

    /**
     * 根据文件相对路径删除相应文件
     * @param $path
     * @return array
     */
    public function delFileByPath ($path):array
    {
        if (file_exists('.' . $path)) {
            $res = unlink('.'.$path);
            return $res ? ['status' => 1, 'msg' => '删除成功'] : ['status' => 0, 'msg' => '删除失败'];
        } else {
            return ['status' => 1, 'msg' => '文件不存在或已删除'];
        }

    }
}
